#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
微信公众号文章爬虫 API 客户端示例
演示如何调用API接口获取文章内容
"""

import requests
import json
import time


class WeChatArticleAPIClient:
    """微信公众号文章API客户端"""
    
    def __init__(self, base_url="http://localhost:5000"):
        """
        初始化API客户端
        :param base_url: API服务器地址
        """
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json',
            'User-Agent': 'WeChatArticleAPIClient/1.0'
        })
    
    def health_check(self):
        """健康检查"""
        try:
            response = self.session.get(f"{self.base_url}/api/health")
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {'error': str(e)}
    
    def crawl_article(self, url, format_type='text'):
        """
        爬取单篇文章
        :param url: 微信公众号文章链接
        :param format_type: 返回格式 (text, html, markdown)
        :return: 文章信息
        """
        try:
            data = {
                'url': url,
                'format': format_type
            }
            
            response = self.session.post(
                f"{self.base_url}/api/crawl",
                json=data,
                timeout=30
            )
            response.raise_for_status()
            return response.json()
        
        except Exception as e:
            return {'success': False, 'error': str(e)}
    
    def batch_crawl_articles(self, urls, format_type='text'):
        """
        批量爬取文章
        :param urls: 微信公众号文章链接列表
        :param format_type: 返回格式 (text, html, markdown)
        :return: 批量爬取结果
        """
        try:
            data = {
                'urls': urls,
                'format': format_type
            }
            
            response = self.session.post(
                f"{self.base_url}/api/batch-crawl",
                json=data,
                timeout=60
            )
            response.raise_for_status()
            return response.json()
        
        except Exception as e:
            return {'success': False, 'error': str(e)}


def example_single_crawl():
    """单篇文章爬取示例"""
    print("=== 单篇文章爬取示例 ===")
    
    client = WeChatArticleAPIClient()
    
    # 健康检查
    health = client.health_check()
    print(f"服务状态: {health}")
    
    # 示例链接（请替换为实际的微信文章链接）
    url = "https://mp.weixin.qq.com/s/S9kSrZ7uavUD21G4ljyhOA"
    
    # 爬取文章（文本格式）
    print(f"\n爬取文章: {url}")
    result = client.crawl_article(url, format_type='text')
    
    if result.get('success'):
        data = result['data']
        print(f"标题: {data['title']}")
        print(f"作者: {data['author']}")
        print(f"发布时间: {data['publish_time']}")
        print(f"内容长度: {data['content_length']} 字符")
        print(f"内容预览: {data['content'][:200]}...")
    else:
        print(f"爬取失败: {result.get('error')}")


def example_batch_crawl():
    """批量文章爬取示例"""
    print("\n=== 批量文章爬取示例 ===")
    
    client = WeChatArticleAPIClient()
    
    # 示例链接列表（请替换为实际的微信文章链接）
    urls = [
        "https://mp.weixin.qq.com/s/example1",
        "https://mp.weixin.qq.com/s/example2",
        "https://mp.weixin.qq.com/s/example3"
    ]
    
    print(f"批量爬取 {len(urls)} 篇文章...")
    result = client.batch_crawl_articles(urls, format_type='text')
    
    if result.get('success'):
        data = result['data']
        print(f"总计: {data['total']} 篇")
        print(f"成功: {data['success_count']} 篇")
        print(f"失败: {data['failed_count']} 篇")
        
        for i, item in enumerate(data['results'], 1):
            print(f"\n文章 {i}: {item['url']}")
            if item['success']:
                article_data = item['data']
                print(f"  标题: {article_data['title']}")
                print(f"  内容长度: {article_data['content_length']} 字符")
            else:
                print(f"  错误: {item['error']}")
    else:
        print(f"批量爬取失败: {result.get('error')}")


def example_different_formats():
    """不同格式示例"""
    print("\n=== 不同格式示例 ===")
    
    client = WeChatArticleAPIClient()
    url = "https://mp.weixin.qq.com/s/S9kSrZ7uavUD21G4ljyhOA"
    
    formats = ['text', 'html', 'markdown']
    
    for format_type in formats:
        print(f"\n--- {format_type.upper()} 格式 ---")
        result = client.crawl_article(url, format_type=format_type)
        
        if result.get('success'):
            data = result['data']
            print(f"标题: {data['title']}")
            print(f"格式: {data['content_type']}")
            print(f"内容长度: {data['content_length']} 字符")
            print(f"内容预览: {data['content'][:150]}...")
        else:
            print(f"爬取失败: {result.get('error')}")
        
        time.sleep(1)  # 避免请求过快


def test_api_endpoints():
    """测试API接口"""
    print("\n=== API接口测试 ===")
    
    base_url = "http://localhost:5000"
    
    # 测试根路径
    try:
        response = requests.get(base_url)
        print(f"GET /: {response.status_code}")
        if response.status_code == 200:
            print(f"响应: {response.json()}")
    except Exception as e:
        print(f"GET / 失败: {e}")
    
    # 测试健康检查
    try:
        response = requests.get(f"{base_url}/api/health")
        print(f"GET /api/health: {response.status_code}")
        if response.status_code == 200:
            print(f"响应: {response.json()}")
    except Exception as e:
        print(f"GET /api/health 失败: {e}")
    
    # 测试错误处理
    try:
        response = requests.post(
            f"{base_url}/api/crawl",
            json={'invalid': 'data'}
        )
        print(f"POST /api/crawl (错误数据): {response.status_code}")
        print(f"错误响应: {response.json()}")
    except Exception as e:
        print(f"错误测试失败: {e}")


def main():
    """主函数"""
    print("微信公众号文章爬虫 API 客户端示例")
    print("=" * 60)
    print("注意: 请确保API服务器正在运行 (python api_server.py)")
    print("=" * 60)
    
    # 运行示例（注释掉避免实际执行）
    # example_single_crawl()
    # example_batch_crawl()
    # example_different_formats()
    test_api_endpoints()
    
    print("\n" + "=" * 60)
    print("示例完成！请根据需要修改示例中的URL并取消注释来运行。")


if __name__ == "__main__":
    main()